CONTENTS | INDEX | PREV | NEXT
 fseek

 NAME
  fseek - seek within a file pointer.

 SYNOPSIS
  #include <stdio.h>

  int error = fseek(fp, offset, how);
  FILE *fp;
  long offset;
  int how;

 FUNCTION
  fseek changes the current seek position within a file.  Offset is
  interpreted according to the how argument:

  how     offset

  SEEK_SET (0)    skip to position relative to beginning of file
  SEEK_CUR (1)    skip to position relative to current position in file
  SEEK_END (2)    skip to position relative to end of file

  So, for example, one may seek to the beginning of a file by
  fseek(fp, 0L, SEEK_SET);, to the end of the file by
  fseek(fp, 0L, SEEK_END); (i.e. calling getc() at this time would
  return an immediate EOF).  You can skip characters in a file
  with something like fseek(fp, 5L, SEEK_CUR); which skips 5 characters.

  Note that when seeking relative to the end of the file, negative
  offsets are used.  For example, to seek to the very last character
  in the file you would use fseek(fp, -1L, SEEK_END);

  fseek returns 0 on success, a negative number on ERROR.  A common
  mistake is to expect fseek to return the new position of the file
  but this is not what is returned.  Use ftell() or fgetpos() to
  determine the current offset into a file.

 NOTE
  refer to the file_pointer manual page for general information

  fseek flushes any buffered write data before seeking.

 EXAMPLE
  /*
   *  print a file backwards
   */

  #include <stdio.h>

  char Buf[4096];

  main(ac, av)
  int ac;
  char **av;
  {
      FILE *fp;
      long pos;

      if (ac == 1) {
      puts("Expected textfile argument");
      exit(1);
      }
      fp = fopen(av[1], "r");
      if (fp == NULL) {
      printf("Unable to open %sn", av[1]);
      exit(1);
      }
      fseek(fp, 0L, SEEK_END);        /*  seek to end     */
      pos = ftell(fp);                /*  size of file    */

      while (pos > 0) {
      long bytes = ((pos > sizeof(Buf)) ? sizeof(Buf) : pos);
      long n;

      fseek(fp, pos - bytes, SEEK_SET);
      n = fread(Buf, 1, bytes, fp);
      if (n != bytes) {
          puts("read error");
          exit(1);
      }
      while (--n >= 0)        /*  dump buffer backwords to stdout */
          putc(Buf[n], stdout);

      pos -= bytes;
      }
      fclose(fp);
      return(0);
  }

 INPUTS
  FILE *fp;       file pointer to seek
  long offset;    offset relative to how
  int how;        0, 1, or 2 (absolute, relative, end-relative)

 RESULTS
  int error;

 SEE ALSO
  ftell, fgetpos, fsetpos, rewind